import 'package:flutter/cupertino.dart';
import 'package:flutter/rendering.dart';

class CustomCenterDemoWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    ///外面包裹一层Align后Container的宽高生效
    // return Align(
    //   child: Container(
    //       width: 200,
    //       height: 200,
    //       child: CustomCenterLayoutWidget(child: Text("文本"))),
    //   alignment: Alignment.topLeft,
    // );

    return Container(
        width: 200,
        height: 200,
        child: CustomCenterLayoutWidget(child: Text("文本")));
  }
}

class CustomCenterLayoutWidget extends SingleChildRenderObjectWidget {
  const CustomCenterLayoutWidget({Key? key, required Widget child})
      : super(key: key, child: child);

  @override
  RenderObject createRenderObject(BuildContext context) {
    return RenderCustomCenterLayout();
  }
}

class RenderCustomCenterLayout extends RenderShiftedBox {
  RenderCustomCenterLayout({RenderBox? child}) : super(child);

  @override
  void performLayout() {
    //1. 先对子组件进行layout，随后获取它的size
    child!.layout(
      constraints.loosen(), //将约束传递给子节点
      parentUsesSize: true, // 因为我们接下来要使用child的size,所以不能为false
    );
    //2.根据子组件的大小确定自身的大小
    size = constraints.constrain(Size(
      constraints.maxWidth == double.infinity
          ? child!.size.width
          : double.infinity,
      constraints.maxHeight == double.infinity
          ? child!.size.height
          : double.infinity,
    ));

    // 3. 根据父节点子节点的大小，算出子节点在父节点中居中之后的偏移，然后将这个偏移保存在
    // 子节点的parentData中，在后续的绘制阶段，会用到。
    BoxParentData parentData = child!.parentData as BoxParentData;
    parentData.offset = ((size - child!.size) as Offset) / 2;
  }
}
